<template>
  <div class="video-wrapper">
    <video
      ref="video0"
      controls
    >
      <source :src="'jianbocheng.mp4'">
    </video>
    <button @click="video0.play()">
      直接播放
    </button>
  </div>
  <div class="video-wrapper">
    <video
      ref="video1"
      controls
    >
      <source :src="'jianbocheng.mp4'">
    </video>
    <button @click="playVideo1InSetTimeout">
      在 setTimeout 中播放
    </button>
    <span v-if="willPlay[1]">即将播放……</span>
  </div>

  <div class="video-wrapper">
    <video
      ref="video2"
      controls
    >
      <source :src="'jianbocheng.mp4'">
    </video>
    <button @click="playVideo2InAsync">
      在 async 函数中播放
    </button>
    <span v-if="willPlay[2]">即将播放……</span>
  </div>

  <div class="video-wrapper">
    <video
      ref="video3"
      controls
    >
      <source :src="'jianbocheng.mp4'">
    </video>
    <button @click="playVideo3InStoredFunction">
      构造 Promise
    </button>
    <button @click="resolveVideo3Promise">
      解决 Promise，让视频播放
    </button>
    <span v-if="willPlay[3]">即将播放……</span>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive } from 'vue';

export default defineComponent({
  name: 'App',

  setup() {
    const videos = [
      ref({} as HTMLVideoElement),
      ref({} as HTMLVideoElement),
      ref({} as HTMLVideoElement),
      ref({} as HTMLVideoElement),
    ];
    let promiseResolver = () => {};
    const willPlay = reactive([
      false, false, false, false,
    ]);

    function playVideo1InSetTimeout() {
      console.log('1000ms 后播放');
      willPlay[1] = true;

      setTimeout(() => {
        videos[1].value.play();
        willPlay[1] = false;
      }, 1000);
    }

    async function playVideo2InAsync() {
      willPlay[2] = true;
      console.log(await Promise.all([fetch('bg.png'), new Promise((r) => setTimeout(r, 1000))]));
      videos[2].value.play();
      willPlay[2] = false;
    }

    async function playVideo3InStoredFunction() {
      const storedPromise = new Promise((resolve) => {
        promiseResolver = resolve as () => void;
      });

      willPlay[3] = true;
      await storedPromise;

      videos[3].value.play();
      willPlay[3] = false;
    }

    function resolveVideo3Promise() {
      promiseResolver();
    }

    return {
      video0: videos[0],
      video1: videos[1],
      video2: videos[2],
      video3: videos[3],

      playVideo1InSetTimeout,
      playVideo2InAsync,
      playVideo3InStoredFunction,
      resolveVideo3Promise,

      willPlay,
    };
  },
});
</script>

<style>
video {
  width: 100%;
  max-height: 100%;
}

.video-wrapper {
  margin: 30px;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgb(224, 243, 255), 1px 1px 5px rgba(42, 61, 111, 0.4);
}
</style>
